package com.merryituxz.o2o.controller.wechat;

import com.merryituxz.o2o.dto.UserAccessToken;
import com.merryituxz.o2o.dto.WechatAuthExecution;
import com.merryituxz.o2o.dto.WechatUser;
import com.merryituxz.o2o.entity.PersonInfo;
import com.merryituxz.o2o.entity.WechatAuth;
import com.merryituxz.o2o.enums.WechatAuthStateEnum;
import com.merryituxz.o2o.service.PersonInfoService;
import com.merryituxz.o2o.service.WechatAuthService;
import com.merryituxz.o2o.util.wechat.WechatUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx12a532cf8febe4e2&redirect_uri=http://merryituxz.work/wechatlogin/logincheck&role_type=1&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect
 */
@Controller
@RequestMapping("wechatlogin")
public class WechatLoginController {
    private static Logger logger = LoggerFactory.getLogger(WechatLoginController.class);

    @Autowired
    private PersonInfoService personInfoService;
    @Autowired
    private WechatAuthService wechatAuthService;
    private static final String FRONTEND = "1"; // 前端
    private static final String SHOPEND = "2";  // 店家

    @RequestMapping(value = "/logincheck", method = RequestMethod.GET)
    public String doGet(HttpServletRequest request, HttpServletResponse response) {
        logger.debug("wechat login GET...");
        // 获取微信公众号传输来的code 通过code获取access_token
        String code = request.getParameter("code");
        String roleType = request.getParameter("state");
        logger.debug("wechat login code: " + code);
        WechatUser user = null;
        String openId = null;
        WechatAuth auth = null;
        if (code != null) {
            UserAccessToken token;
            try {
                // 通过code获取access_token
                token = WechatUtil.getUserAccessToken(code);
                logger.debug("wechat login token: " + token.toString());
                String accessToken = token.getAccessToken();
                // 获取openId
                openId = token.getOpenId();
                // 通过access_token和openId获取用户信息
                user = WechatUtil.getUserInfo(accessToken, openId);
                logger.debug("wechat login user: " + user.toString());
                request.getSession().setAttribute("openId", openId);
                auth = wechatAuthService.getWechatAuthByOpenId(openId);
            } catch (Exception e) {
                logger.error("error in getUserAccessToken or getUserInfo or fingByOpenId: " + e.getMessage());
                e.printStackTrace();
            }
        }
        // 若微信账号为空则自动注册微信账号及用户信息
        if (auth == null) {
            PersonInfo personInfo = WechatUtil.getPersonInfoFromRequest(user);
            auth = new WechatAuth();
            auth.setOpenId(openId);
            if (FRONTEND.equals(roleType)) {
                personInfo.setUserType(1);
            } else {
                personInfo.setUserType(2);
            }
            auth.setPersonInfo(personInfo);
            WechatAuthExecution wechatAuthExecution = wechatAuthService.register(auth);
            if (wechatAuthExecution.getState() != WechatAuthStateEnum.SUCCESS.getState()) {
                return null;
            } else {
                personInfo = personInfoService.getPersonInfoById(auth.getPersonInfo().getUserId());
                request.getSession().setAttribute("user", personInfo);
            }
        } else {
            request.getSession().setAttribute("user", auth.getPersonInfo());
        }

        if (FRONTEND.equals(roleType)) {
            return "frontend/index";
        } else {
            return "shop/shoplist";
        }
    }
}
